<template>
  <div class="novel-role">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" :icon="ArrowLeft" circle />
        <h1 class="page-title">人物管理</h1>
      </div>
      <div class="header-right">
        <el-button @click="testApiConnection" type="info" size="small">
          测试API
        </el-button>
        <el-button @click="addTestData" type="warning" size="small">
          测试数据
        </el-button>
        <el-button type="primary" @click="handleAddRole" :icon="Plus">
          添加人物
        </el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索人物名称..."
        :prefix-icon="Search"
        clearable
        @input="handleSearch"
        class="search-input"
      />
    </div>

    <!-- 人物卡片网格 -->
    <div class="characters-grid" v-loading="loading">
      <div 
        v-for="role in filteredRoles" 
        :key="role.id" 
        class="character-card"
        @click="handleViewRole(role)"
      >
        <div class="character-avatar">
          <el-image
            :src="getImageUrl(role.roleImg)"
            :alt="role.roleName"
            fit="cover"
            class="avatar-image"
          >
            <template #error>
              <div class="avatar-placeholder">
                <el-icon><User /></el-icon>
              </div>
            </template>
          </el-image>
        </div>
        <div class="character-info">
          <h3 class="character-name">{{ role.roleName }}</h3>
          <p class="character-desc">{{ role.roleDetail || '暂无描述' }}</p>
        </div>
        <div class="character-actions">
          <el-button 
            size="small" 
            @click.stop="handleEditRole(role)"
            :icon="Edit"
          >
            编辑
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click.stop="handleDeleteRole(role)"
            :icon="Delete"
          >
            删除
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && filteredRoles.length === 0" class="empty-state">
      <el-empty description="暂无人物数据">
        <el-button type="primary" @click="handleAddRole">添加第一个人物</el-button>
      </el-empty>
    </div>

    <!-- 添加/编辑人物弹窗 -->
    <el-dialog
      v-model="showRoleDialog"
      :title="isEdit ? '编辑人物' : '添加人物'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="roleForm" 
        :rules="roleRules" 
        ref="roleFormRef" 
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="roleName" required>
              <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="小说ID" prop="novelId" required>
              <el-input-number 
                v-model="roleForm.novelId" 
                :min="1" 
                :precision="0"
                placeholder="请输入小说ID"
                style="width: 100%"
                controls-position="right"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="角色描述" prop="roleDetail">
          <el-input 
            v-model="roleForm.roleDetail" 
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="角色衣着" prop="roleDress">
          <el-input 
            v-model="roleForm.roleDress" 
            type="textarea"
            :rows="2"
            placeholder="请输入角色衣着描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="绘画提示词" prop="rolePromt">
          <el-input 
            v-model="roleForm.rolePromt" 
            type="textarea"
            :rows="3"
            placeholder="请输入角色绘画提示词"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色图片" prop="roleImg">
              <FileUpload
                v-model="roleForm.roleImg"
                :action="'/common/upload'"
                :file-type="['jpg', 'jpeg', 'png', 'gif']"
                :file-size="5"
                :limit="1"
                :is-show-tip="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参考图片" prop="refImg">
              <FileUpload
                v-model="roleForm.refImg"
                :action="'/common/upload'"
                :file-type="['jpg', 'jpeg', 'png', 'gif']"
                :file-size="5"
                :limit="1"
                :is-show-tip="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelRole">取消</el-button>
          <el-button type="primary" @click="submitRole" :loading="submitting">
            <el-icon><Check /></el-icon>
            {{ isEdit ? '确定修改' : '确定添加' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 人物详情弹窗 -->
    <el-dialog
      v-model="showDetailDialog"
      title="人物详情"
      width="600px"
    >
      <div v-if="selectedRole" class="role-detail">
        <div class="detail-avatar">
          <el-image
            :src="getImageUrl(selectedRole.roleImg)"
            :alt="selectedRole.roleName"
            fit="cover"
            class="detail-image"
          >
            <template #error>
              <div class="detail-placeholder">
                <el-icon><User /></el-icon>
              </div>
            </template>
          </el-image>
        </div>
        <div class="detail-info">
          <h2>{{ selectedRole.roleName }}</h2>
          <div class="detail-item">
            <label>角色描述：</label>
            <p>{{ selectedRole.roleDetail || '暂无描述' }}</p>
          </div>
          <div class="detail-item">
            <label>角色衣着：</label>
            <p>{{ selectedRole.roleDress || '暂无描述' }}</p>
          </div>
          <div class="detail-item">
            <label>绘画提示词：</label>
            <p>{{ selectedRole.rolePromt || '暂无提示词' }}</p>
          </div>
          <div v-if="selectedRole.refImg" class="detail-item">
            <label>参考图片：</label>
            <el-image
              :src="getImageUrl(selectedRole.refImg)"
              :alt="selectedRole.roleName + '参考图'"
              fit="cover"
              class="ref-image"
            />
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, 
  Plus, 
  Search, 
  Edit, 
  Delete, 
  Check, 
  User 
} from '@element-plus/icons-vue'
import FileUpload from '@/components/FileUpload/index.vue'
import { listRole, addRole, updateRole, delRole } from '@/api/novel/role'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const roles = ref([])
const showRoleDialog = ref(false)
const showDetailDialog = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const selectedRole = ref(null)

// 角色表单
const roleForm = reactive({
  id: null,
  novelId: null,
  roleName: '',
  roleDetail: '',
  roleDress: '',
  rolePromt: '',
  roleImg: '',
  refImg: ''
})

// 表单验证规则
const roleRules = reactive({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 1, max: 50, message: '角色名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  novelId: [
    { required: true, message: '请输入小说ID', trigger: 'blur' },
    { type: 'number', message: '小说ID必须是数字', trigger: 'blur' }
  ]
})

// 表单引用
const roleFormRef = ref()

// 计算属性 - 过滤后的人物列表
const filteredRoles = computed(() => {
  if (!searchKeyword.value) {
    return roles.value
  }
  return roles.value.filter(role => 
    role.roleName.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 获取图片URL
const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  if (imagePath.startsWith('http')) return imagePath
  return `/dev-api${imagePath}`
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑在计算属性中处理
}

// 加载人物列表
const loadRoles = async () => {
  try {
    loading.value = true
    console.log('Loading roles...')
    const response = await listRole({})
    console.log('Roles response:', response)
    if (response.code === 200) {
      roles.value = response.rows || []
      console.log('Loaded roles:', roles.value)
    } else {
      ElMessage.error(response.msg || '加载人物列表失败')
    }
  } catch (error) {
    console.error('Load roles error:', error)
    ElMessage.error('加载人物列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 添加人物
const handleAddRole = () => {
  isEdit.value = false
  resetForm()
  showRoleDialog.value = true
}

// 编辑人物
const handleEditRole = (role) => {
  isEdit.value = true
  roleForm.id = role.id
  roleForm.novelId = role.novelId
  roleForm.roleName = role.roleName
  roleForm.roleDetail = role.roleDetail || ''
  roleForm.roleDress = role.roleDress || ''
  roleForm.rolePromt = role.rolePromt || ''
  roleForm.roleImg = role.roleImg || ''
  roleForm.refImg = role.refImg || ''
  
  if (roleFormRef.value) {
    roleFormRef.value.clearValidate()
  }
  
  showRoleDialog.value = true
}

// 查看人物详情
const handleViewRole = (role) => {
  selectedRole.value = role
  showDetailDialog.value = true
}

// 删除人物
const handleDeleteRole = async (role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除人物"${role.roleName}"吗？删除后无法恢复！`, 
      '删除确认', 
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    console.log('Deleting role:', role)
    const response = await delRole(role.id)
    console.log('Delete response:', response)
    
    if (response.code === 200) {
      ElMessage.success('人物删除成功')
      loadRoles()
    } else {
      ElMessage.error(response.msg || '人物删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete role error:', error)
      ElMessage.error('人物删除失败: ' + error.message)
    }
  }
}

// 提交表单
const submitRole = async () => {
  if (!roleFormRef.value) {
    console.error('Form ref not found')
    return
  }
  
  try {
    console.log('Validating form...')
    await roleFormRef.value.validate()
    console.log('Form validation passed')
  } catch (error) {
    console.error('Form validation failed:', error)
    ElMessage.error('请完善必填信息')
    return
  }
  
  try {
    submitting.value = true
    console.log('Submitting role form:', roleForm)
    console.log('Is edit mode:', isEdit.value)
    
    const response = isEdit.value 
      ? await updateRole(roleForm)
      : await addRole(roleForm)
    
    console.log('Submit response:', response)
      
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '人物修改成功' : '人物添加成功')
      showRoleDialog.value = false
      loadRoles()
    } else {
      ElMessage.error(response.msg || (isEdit.value ? '人物修改失败' : '人物添加失败'))
    }
  } catch (error) {
    console.error('Submit role error:', error)
    ElMessage.error((isEdit.value ? '人物修改失败' : '人物添加失败') + ': ' + error.message)
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancelRole = () => {
  showRoleDialog.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  roleForm.id = null
  roleForm.novelId = null
  roleForm.roleName = ''
  roleForm.roleDetail = ''
  roleForm.roleDress = ''
  roleForm.rolePromt = ''
  roleForm.roleImg = ''
  roleForm.refImg = ''
  
  if (roleFormRef.value) {
    roleFormRef.value.clearValidate()
  }
}

// 测试API连接
const testApiConnection = async () => {
  try {
    console.log('Testing API connection...')
    const response = await listRole({})
    console.log('API test response:', response)
    ElMessage.success('API连接正常: ' + JSON.stringify(response))
  } catch (error) {
    console.error('API test error:', error)
    ElMessage.error('API连接失败: ' + error.message)
  }
}

// 添加测试数据
const addTestData = () => {
  const testRole = {
    id: Date.now(),
    novelId: 1,
    roleName: '测试角色',
    roleDetail: '这是一个测试角色',
    roleDress: '测试服装',
    rolePromt: '测试提示词',
    roleImg: '',
    refImg: ''
  }
  roles.value.push(testRole)
  ElMessage.success('已添加测试数据')
}

// 页面加载
onMounted(() => {
  loadRoles()
})
</script>

<style scoped lang="scss">
.novel-role {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: white;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;

    .page-title {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }
  }
}

.search-bar {
  margin-bottom: 24px;
  background: white;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .search-input {
    max-width: 400px;
  }
}

.characters-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.character-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  }

  .character-avatar {
    text-align: center;
    margin-bottom: 16px;

    .avatar-image {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      border: 3px solid #f0f0f0;
    }

    .avatar-placeholder {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      background: #f0f0f0;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32px;
      color: #999;
    }
  }

  .character-info {
    text-align: center;
    margin-bottom: 16px;

    .character-name {
      margin: 0 0 8px 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .character-desc {
      margin: 0;
      font-size: 14px;
      color: #666;
      line-height: 1.4;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
  }

  .character-actions {
    display: flex;
    gap: 8px;
    justify-content: center;
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.role-detail {
  .detail-avatar {
    text-align: center;
    margin-bottom: 24px;

    .detail-image {
      width: 120px;
      height: 120px;
      border-radius: 50%;
      border: 4px solid #f0f0f0;
    }

    .detail-placeholder {
      width: 120px;
      height: 120px;
      border-radius: 50%;
      background: #f0f0f0;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 48px;
      color: #999;
    }
  }

  .detail-info {
    h2 {
      text-align: center;
      margin: 0 0 20px 0;
      color: #333;
    }

    .detail-item {
      margin-bottom: 16px;

      label {
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 4px;
      }

      p {
        margin: 0;
        color: #666;
        line-height: 1.6;
      }

      .ref-image {
        width: 100%;
        max-width: 200px;
        border-radius: 8px;
        margin-top: 8px;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}

// 响应式设计
@media (max-width: 768px) {
  .characters-grid {
    grid-template-columns: 1fr;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;

    .header-left {
      justify-content: center;
    }
  }
}
</style>
